<?php
/***********************************************************
 * 网站信息
 * @作者 pcfcms <1131680521@qq.com>
 * @版权 广州市春风科技有限公司
 * @主页 http://www.pcfcms.com
 * @时间 2019年12月21日
***********************************************************/
namespace app\admin\controller\system;
use app\admin\controller\Base;
use think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
use lunzi\TpSms;
class Web extends Base
{
    public $popedom = '';
    public function initialize() {
        parent::initialize();
        $ctl_act = Request::controller().'/index';
        $this->popedom = appfile_popedom($ctl_act);
    }
	
    //网站设置
    public function index()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        $inc_type =  'web';
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('post.');
            $param['web_keywords'] = str_replace('，', ',', $param['web_keywords']);
            $param['web_description'] = filter_line_return($param['web_description']);
            //网站根网址
            $web_basehost = rtrim($param['web_basehost'], '/');
            if (!is_http_url($web_basehost) && !empty($web_basehost)) {
                $web_basehost = $this->request->scheme().'://'.$web_basehost;
            }
            $param['web_basehost'] = $web_basehost;
            //网站LOGO
            if (!empty($param['old_web_logo']) && !empty($param['web_logo']) && !is_http_url($param['web_logo'])) {
                $image_ext_str = config("params.image_ext");
                $image_ext_match = str_replace(',','|',$image_ext_str);
                $img_match = '/(\w+\.(?:'.$image_ext_match.'))$/i';
                preg_match($img_match, $param['web_logo'],$matches);
                preg_match($img_match, $param['old_web_logo'],$matches_old);
                $source = preg_replace('#^/#i', '', $param['web_logo']);
                $destination = preg_replace('#^/#i', '', $param['old_web_logo']);
                if (file_exists($source) && @copy($source, '.'.$destination)) {
                    $param['web_logo'] = $destination;
                    @unlink($source);
                }
            }
            unset($param['old_web_logo']);
            //浏览器地址图标
            if (!empty($param['web_ico']) && !is_http_url($param['web_ico'])) {
                $source = './'.preg_replace('#^/#i', '', $param['web_ico']);
                $destination = '/favicon.ico';
                if (file_exists($source) && @copy($source, '.'.$destination)) {
                    $param['web_ico'] = $destination;
                    @unlink($source);
                }
            }
            tpCache($inc_type, $param);
            write_global_params(); //写入全局内置参数
            // 清除缓存
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache($inc_type);
        //自定义变量
        $pcf_row = Db::name('config_attribute')->field('a.attr_id, a.attr_name, a.attr_var_name, a.attr_input_type, b.value, b.id, b.name')
            ->alias('a')
            ->join('config b', 'b.name = a.attr_var_name', 'LEFT')
            ->where(['a.inc_type' => $inc_type,'b.is_del' => 0])
            ->order('a.attr_id asc')
            ->select()->toArray();
        $this->assign('pcf_row',$pcf_row);
        $this->assign('config',$config);
        return $this->fetch('index');
    }
	
    //核心设置
    public function web2()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        $inc_type = 'web';
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('post.');
            //CMS安装目录
            empty($param['web_cmspath']) && $param['web_cmspath'] = base_path(); //支持子目录
            $web_cmspath = trim($param['web_cmspath'], '/');
            $web_cmspath = str_replace("\/", "/", $web_cmspath);
            $web_cmspath = str_replace("/", "\\", $web_cmspath);
            $web_cmspath = !empty($web_cmspath) ? $web_cmspath : '';
            $param['web_cmspath'] = $web_cmspath;

            //自定义后台路径名
            $adminbasefile = trim($param['adminbasefile']).'.php'; //新的文件名
            $param['web_adminbasefile'] = root_path().'public/'.$adminbasefile; //支持子目录 
            $param['web_adminbasefile'] = str_replace("\/", "/", $param['web_adminbasefile']);
            $param['web_adminbasefile'] = str_replace("/", "\\", $param['web_adminbasefile']);
            $adminbasefile_old = trim($param['adminbasefile_old']).'.php'; //旧的文件名
            unset($param['adminbasefile']);
            unset($param['adminbasefile_old']);
            if ('index.php' == $adminbasefile) {
                $result = ['status' => false, 'msg' => '后台路径禁止使用index'];
                return $result;
            }

            //后台LOGO
            $web_adminlogo = $param['web_adminlogo'];
            $web_adminlogo_old = tpCache('web.web_adminlogo');
            if ($web_adminlogo != $web_adminlogo_old && !empty($web_adminlogo)) {
                if(tpCache('web.web_is_authortoken') > 0){
                    $image_ext_str = config("params.image_ext");
                    $image_ext_match = str_replace(',','|',$image_ext_str); 
                    $img_match = '/(\w+\.(?:'.$image_ext_match.'))$/i';
                    preg_match($img_match, $web_adminlogo,$matches);
                    preg_match($img_match, $web_adminlogo_old,$matches_old);
                    $source = preg_replace('#^#i', '', $web_adminlogo); //支持子目录
                    $destination = '/admin/assets/images/logo.png';
                    if (@copy('.'.$source , '.'.$destination)) {
                        $param['web_adminlogo'] = $destination;
                        @unlink('.'.$source);
                    }
                }else{
                    $result = ['status' => false, 'msg' => '授权用户才可以修改后台LOGO！'];
                    return $result;
                }
            }                
            
            tpCache($inc_type,$param);
            write_global_params(); //写入全局内置参数
            $refresh = false;
            $gourl = request::domain().'/'.$adminbasefile; //支持子目录
            //更改自定义后台路径名
            if ($adminbasefile_old != $adminbasefile && eyPreventShell($adminbasefile_old)) {
                if (file_exists($adminbasefile_old)) {
                    if(rename($adminbasefile_old, $adminbasefile)) {
                        $refresh = true;
                    }
                } else {
                    $result = ['status' => false, 'msg' => '根目录{$adminbasefile_old}文件不存在！'];
                    return $result;
                }
            }
            // 清除缓存
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            //刷新整个后台
            if ($refresh) {
                $result = ['status' => true, 'msg' => '操作成功', 'url' => $gourl, 'target' => '_parent'];
                return $result;
            }
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache($inc_type);
        //自定义后台路径名
        $baseFile = explode('/', request::baseFile());
        $web_adminbasefile = end($baseFile);
        $adminbasefile = preg_replace('/^(.*)\.([^\.]+)$/i', '$1', $web_adminbasefile);
        $this->assign('adminbasefile', $adminbasefile);
        //数据库备份目录
        $sqlbackuppath = $config['web_sqldatapath'];
        $this->assign('sqlbackuppath', $sqlbackuppath);
        $this->assign('config',$config);
        return $this->fetch();
    }
	
    //附件设置
    public function basic()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        $inc_type =  'basic';
        //文件上传最大限制
        $maxFileupload = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 0;
        if (0 !== $maxFileupload) {
            $max_filesize = unformat_bytes($maxFileupload);
            $max_filesize = $max_filesize / 1024 / 1024; //单位是MB的大小
        } else {
            $max_filesize = 500;
        }
        $max_sizeunit = 'MB';
        $maxFileupload = $max_filesize.$max_sizeunit;
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('post.');
            $param['file_size'] = intval($param['file_size']);
            if (0 < $max_filesize && $max_filesize < $param['file_size']) {
                $result = ['status' => false, 'msg' => "附件上传大小超过空间的最大限制".$maxFileupload];
                return $result;
            }
            // 过滤php扩展名的附件类型
            $image_type = explode('|', $param['image_type']);
            foreach ($image_type as $key => $val) {
                $val = trim($val);
                if (stristr($val, 'php') || empty($val)) {
                    unset($image_type[$key]);
                }
            }
            $param['image_type'] = implode('|', $image_type);
            $file_type = explode('|', $param['file_type']);
            foreach ($file_type as $key => $val) {
                $val = trim($val);
                if (stristr($val, 'php') || empty($val)) {
                    unset($file_type[$key]);
                }
            }
            $param['file_type'] = implode('|', $file_type);
            $media_type = explode('|', $param['media_type']);
            foreach ($media_type as $key => $val) {
                $val = trim($val);
                if (stristr($val, 'php') || empty($val)) {
                    unset($media_type[$key]);
                }
            }
            $param['media_type'] = implode('|', $media_type);
            tpCache($inc_type,$param);
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache($inc_type);
        $this->assign('config',$config);//当前配置项
        $this->assign('max_filesize',$max_filesize);// 文件上传最大字节数
        $this->assign('max_sizeunit',$max_sizeunit);// 文件上传最大字节的单位
        return $this->fetch();
    }
	
    //自定义变量列表
    public function customvar_index()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        $list = array();
        $pcfattr_var_names = array();
        $keywords = input('keywords/s');
        $attr_var_names = Db::name('config')->field('name')->where(['is_del' => 0])->select()->toArray();
        foreach ($attr_var_names as $key => $rs){
            $pcfattr_var_names[$rs['name']]['name'] = $rs['name'];
        }
        $list = Db::name('config_attribute')->alias('a')
            ->field('a.*, b.id')
            ->join('config b', 'b.name = a.attr_var_name')
            ->where('b.is_del', 0)
            ->order('a.attr_id asc')
            ->select()->toArray(); 
        $this->assign('list',$list);
        return $this->fetch();
    }
	
    //保存自定义变量
    public function customvar_save()
    {
        //验证修改权限
        if(!$this->popedom["add"]){
            if(config('params.auth_msg.test')){
                $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                return $result;
            }else{
                $result = ['status' => false, 'msg' => config('params.auth_msg.add')];
                return $result;                    
            }
        }
        //验证修改权限
        if(!$this->popedom["modify"]){
            if(config('params.auth_msg.test')){
                $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                return $result;
            }else{
                $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                return $result;                    
            }
        }
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        if (Request::isPost()) {
            $post = input('post.');
            $addData = $editData = $configData = [];
            foreach ($post['attr_name'] as $key => $val) {
                $attr_name  = trim($val);
                $attr_input_type = intval($post['attr_input_type'][$key]);
                if (empty($post['attr_id'][$key])) {
                    $addData[] = [
                        'inc_type'  => 'web',
                        'attr_name'  => $attr_name,
                        'attr_input_type' => $attr_input_type,
                        'add_time' => getTime(),
                    ];
                } else {
                    $attr_id = intval($post['attr_id'][$key]);
                    $editData[] = [
                        'attr_id'  => $attr_id,
                        'inc_type'  => 'web',
                        'attr_name'  => $attr_name,
                        'attr_var_name' => 'web_attr_'.$attr_id,
                        'attr_input_type' => $attr_input_type,
                        'update_time' => getTime(),
                    ];
                }
            }
            if (!empty($addData)) {
                foreach ($addData as $k1 => $v1) {
                    $attr_id = Db::name('config_attribute')->insertGetId($v1);
                    $addData[$k1]['attr_id'] = $attr_id;
                    $addData[$k1]['attr_var_name'] = 'web_attr_'.$attr_id;
                    $addData[$k1]['update_time'] = getTime();
                    unset($addData[$k1]['add_time']);
                }
                $editData = array_merge($editData, $addData);
            }
            if (!empty($editData)) {
                foreach($editData as $k2 => $v2){
                    Db::name('config_attribute')->save($v2);
                }
                //保存到config表 更新缓存
                foreach ($addData as $key => $val) {
                    $configData[$val['attr_var_name']] = '';
                }
                !empty($configData) && tpCache('web', $configData);
                $result = ['status' => true, 'msg' => '操作成功', 'url' => Request::baseFile().'/system.web/index'];
                return $result;
            } 
        }
        $result = ['status' => false, 'msg' => '非法访问！'];
        return $result;
    }
	
    //删除自定义变量
    public function customvar_del()
    {
        //验证修改权限
        if(!$this->popedom["delete"]){
            if(config('params.auth_msg.test')){
                $result = ['code' => 0, 'msg' => config('params.auth_msg.pcfcms')];
                return $result;
            }else{
                $result = ['code' => 0, 'msg' => config('params.auth_msg.delete')];
                return $result;                    
            }
        }
        //防止php超时
        function_exists('set_time_limit') && set_time_limit(0);
        $id_arr = input('del_id/a');
        $id_arr = eyIntval($id_arr);
        if(Request::isPost() && !empty($id_arr)){
            $attr_var_name = Db::name('config')->where('id',$id_arr['0'])->value('name');
            $r = Db::name('config')->where('name', $attr_var_name)->update(array('is_del'=>1, 'update_time'=>getTime()));
            if($r){
                Db::name('config_attribute')->where('attr_var_name', $attr_var_name)->update(array('update_time'=>getTime()));
                $result = ['code' => 1, 'msg' => '删除成功'];
                return $result;
            }else{
                $result = ['code' => 0, 'msg' => '删除失败'];
                return $result;            
            }
        }else{
            $result = ['code' => 0, 'msg' => '参数有误'];
            return $result; 
        }
    }

    // 邮箱配置
    public function weapp_email()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('param.');
            if(!isset($param['smtp_syn_weapp'])){
                $param['smtp_syn_weapp'] = 0;
            }
            tpCache("smtp",$param);
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache("smtp");
        $this->assign('config',$config);//当前配置项
        return $this->fetch();
    }

    //测试邮箱
    public function send_email()
    {
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            // 查询扩展是否开启
            $openssl_funcs = get_extension_funcs('openssl');
            if (!$openssl_funcs) {
                return ['status'=>false, 'msg'=>"请联系空间商，开启php的 <font color='red'>openssl</font> 扩展！"];
            }
            // 是否填写邮件配置
            $smtp_config = tpCache('smtp');
            if($smtp_config['smtp_syn_weapp'] == 1 || !empty($smtp_config['smtp_syn_weapp'])){
                unset($smtp_config['smtp_test']);
                foreach ($smtp_config as $key => $val) {
                    if (empty($val)) {
                        return ['status'=>false, 'msg'=>"该功能待开放，网站管理员尚未完善邮件配置！"];
                    }
                }
            }else{
                return ['status'=>false, 'msg'=>"后台邮箱功能没有开启！"];
            }
            $param = input('param.');
            $web_name = '测试邮箱-'.tpCache('web.web_name');
            $content = "<p style='text-align:left;'>我是一封测邮箱！</p>";
            $pcfcmssend = pcfcmssend_email($param['email'], $web_name, $content, $smtp_config);
            if($pcfcmssend['code'] ==1 && $pcfcmssend['msg'] ="发送成功"){
                $result = ['status' => true, 'msg' => '发送成功'];
            }else{
                $result = ['status' => false, 'msg' => '发送失败！'];
            }
            return $result;
        }
    }

    // 短信配置
    public function weapp_sms()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('param.');
            if(!isset($param['sms_syn_weapp'])){
                $param['sms_syn_weapp'] = 0;
            }
            tpCache("sms",$param);
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache("sms");
        $this->assign('config',$config);//当前配置项
        return $this->fetch();
    }

    //测试短信
    public function send_sms()
    {
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            // 是否填写短信配置
            $sms_config = tpCache('sms');
            if($sms_config['sms_syn_weapp'] == 1 || !empty($sms_config['sms_syn_weapp'])){
                unset($sms_config['sms_content']);
                unset($sms_config['sms_test']);
                foreach ($sms_config as $key => $val) {
                    if (empty($val)) {
                        return ['status'=>false, 'msg'=>"该功能待开放，网站管理员尚未完善短信配置！"];
                    }
                }
            }else{
                return ['status'=>false, 'msg'=>"后台短信功能没有开启！"];
            }
            $tpSms = new TpSms();
            $param = input('param.');
            $mobile = $param['mobile'];
            $yanzhengma = mt_rand(100000,999999);
            $sms_appkey = $sms_config['sms_appkey'];
            $sms_secretkey = $sms_config['sms_secretkey'];
            if(isset($sms_config['sms_content']) && !empty($sms_config['sms_content'])){
               $content = $sms_config['sms_content'];//短信内容
            }else{
               $content ="【pcfcms】验证码为：".$yanzhengma."。尊敬的客户，请在5分钟之内输入该手机动态验证码，过期自动失效。";//短信内容 
            }
            $json = $tpSms->sendsms('1555',$sms_appkey,$sms_secretkey,$mobile,$content);
            $result1 = json_decode($json, true);
            if($result1['returnstatus'] = "success" && $result1['message'] = "ok"){
                $result = ['status' => true, 'msg' => '发送成功'];
            }else{
                $result = ['status' => false, 'msg' => '发送失败！'];
            }
            return $result;
        }
    }

    // 第三方登录配置
    public function weapp_social()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('param.');
            if(!isset($param['qq_syn_weapp'])){
                $param['qq_syn_weapp'] = 0;
            }
            tpCache("qq",$param);
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache("qq");
        $this->assign('config',$config);//当前配置项
        return $this->fetch();
    }    

    // 支付配置
    public function weapp_pay()
    {
        //验证查看权限
        if(!$this->popedom["list"]){
            return $this->errorNotice(config('params.auth_msg.list'),true,3,false);
        }
        if (Request::isAjax()) {
            //验证修改权限
            if(!$this->popedom["modify"]){
                if(config('params.auth_msg.test')){
                    $result = ['status' => false, 'msg' => config('params.auth_msg.pcfcms')];
                    return $result;
                }else{
                    $result = ['status' => false, 'msg' => config('params.auth_msg.modify')];
                    return $result;                    
                }
            }
            $param = input('param.');
            if(!isset($param['wxpay_syn_weapp'])){
                $param['wxpay_syn_weapp'] = 0;
            }
            tpCache("wxpay",$param);
            Cache::clear();//清除数据缓存文件
            $admin_temp = glob(root_path() . 'runtime/admin/temp/'. '*.php');//清除后台临时文件缓存
            array_map('unlink', $admin_temp);
            $result = ['status' => true, 'msg' => '操作成功'];
            return $result;
        }
        $config = tpCache("wxpay");
        $this->assign('config',$config);//当前配置项
        return $this->fetch();
    }

}
